﻿using BLL;
using HslCommunication.MQTT;
using HslCommunication.Profinet.Melsec.Helper;
using Model;
using MQTTnet;
using MQTTnet.Client;
using MQTTnet.Client.Options;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Drawing;
using System.Globalization;
using System.Linq;
using System.Runtime.InteropServices;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace MachineStatusClient
{
    public partial class DJUserControl : UserControl
    {
        BContentToSqlServer bts = new BContentToSqlServer();
        private string time;
        private static string MqttIp = "192.168.190.21";
        private static int MqttPort =6001;
        private static string MqttTopic = "ZXJDJData";
        // MQTT 客户端
        private static IMqttClient _mqttClient;
        public DJUserControl()
        {
            InitializeComponent();
            dataGridView3.CellDoubleClick += dataGridView3_CellContentClick;


            //// 设置日期时间选择器格式
            //dateTimePickerStart.Format = DateTimePickerFormat.Custom;
            //dateTimePickerStart.CustomFormat = "yyyy-MM-dd";
            //dateTimePickerStart.ShowUpDown = true;  // 启用时间选择模式

            //dateTimePickerEnd.Format = DateTimePickerFormat.Custom;
            //dateTimePickerEnd.CustomFormat = "yyyy-MM-dd";
            //dateTimePickerEnd.ShowUpDown = true;


            // 添加Enter事件处理程序
            //dateTimePickerStart.Enter += Control_Enter;
            //dateTimePickerEnd.Enter += Control_Enter;
            textBoxCZRY.Enter += Control_Enter;
        }

        private void DJUserControl_Load(object sender, EventArgs e)
        {
            dateTimePickerStart.Value = DateTime.Now.AddDays(-7);
            dateTimePickerEnd.Value = DateTime.Now;
            // 初始加载时使用默认条件查询
            BindWorkOrdersToDataGridView(new SearchModel
            {
                StartTime = dateTimePickerStart.Value,
                EndTime = dateTimePickerEnd.Value,
                CZRY = "" // 操作员留空
            });
        }
        /// <summary>
        /// 新增点检记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private async void buttonInsertDJ_Click(object sender, EventArgs e)
        {
            using (AddForm addForm = new AddForm())
            {
                if (addForm.ShowDialog() == DialogResult.OK)
                {
                    // 这里可以添加数据刷新逻辑（可选）
                    //BindWorkOrdersToDataGridView();
                    BindWorkOrdersToDataGridView(new SearchModel
                    {
                        StartTime = dateTimePickerStart.Value,
                        EndTime = DateTime.Now,
                        CZRY = "" //textBoxCZRY.Text.Trim()
                    });
                    //MessageBox.Show("新增成功！");
                    //执行MQTT去同步点检记录到服务器
                    await SetupMqttClient();
                }
            }
        }

        private async Task SetupMqttClient()
        {
            try
            {
                _mqttClient = new MqttFactory().CreateMqttClient();
                MqttClientOptionsBuilder builder = new MqttClientOptionsBuilder()
                       .WithClientId("CNC-SYS")
                       .WithCommunicationTimeout(TimeSpan.FromMilliseconds(50000))
                       .WithTcpServer(MqttIp, MqttPort);
                //if (ck_UserPwd.Checked)
                //{
                builder.WithCredentials("SYS", "1");
                //}
                IMqttClientOptions option = builder.Build();
                await _mqttClient.ConnectAsync(option);
                //Console.WriteLine(MqttIp + "MQTT 连接成功");
                ProcessData();//查询数据并同步
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"MQTT 连接失败");
            }

        }

        private async void ProcessData()
        {
            try
            {
                // 1. 查询数据
                var data = FetchData();
                if (data.Count == 0)
                {
                    //Console.WriteLine($"{DateTime.Now}: 无新数据");
                    return;
                }

                // 2. MQTT 推送
               // Console.WriteLine($"{DateTime.Now}: 查询到 {data.Count} 条数据，开始推送...");
                var isPushSuccess = await PublishData(data);

                if (isPushSuccess)
                {
                    // 3. 修改迁移数据
                    UpdateData(data);
                    //Console.WriteLine($"{DateTime.Now}: 数据迁移删除完成");
                }
                else
                {
                   // Console.WriteLine($"{DateTime.Now}: MQTT 推送失败，数据保留");
                }
            }
            catch (Exception ex)
            {
                //Console.WriteLine($"{DateTime.Now}: 处理失败 - {ex.Message}");
            }
        }

        private List<ZXJDataModel> FetchData()
        {
            var data = new List<ZXJDataModel>();
            var dt = bts.GetDJData();
            if (dt != null && dt.Count > 0)
            {
                foreach (var item in dt)
                {
                    data.Add(new ZXJDataModel
                    {
                        MachineId = item.MachineId,
                        JJTZKG = item.JJTZKG,
                        JSQ = item.JSQ,
                        RJJM = item.RJJM,
                        XJTX = item.XJTX,
                        FGJP = item.FGJP,
                        ZDMD = item.ZDMD,
                        THJC = item.THJC,
                        BTHJC = item.BTHJC,
                        THZZ = item.THZZ,
                        JZQG = item.JZQG,
                        AQMZZ = item.AQMZZ,
                        JTBMZW = item.JTBMZW,
                        GQGYZZ = item.GQGYZZ,
                        JTSFLQ = item.JTSFLQ,
                        QYB = item.QYB,
                        YSKQ = item.YSKQ,
                        DZDJ = item.DZDJ,
                        SDZH = item.SDZH,
                        XRHBW = item.XRHBW,
                        ZDP = item.ZDP,
                        TRCDBF = item.TRCDBF,
                        PD = item.PD,
                        LDJC = item.LDJC,
                        CZRY = item.CZRY,
                        ZZ = item.ZZ,
                        JXBQ = item.JXBQ,
                        GetTime = Convert.ToDateTime(item.GetTime),
                        DJDate = Convert.ToDateTime(item.DJDate),
                        DJType = item.DJType,
                        ID = item.ID
                    });
                }
            }


            return data;
        }
        /// <summary>
        /// 修改同步的数据
        /// </summary>
        /// <param name="data"></param>
        private void UpdateData(List<ZXJDataModel> data)
        {
            List<string> idList = data.Where(d => !string.IsNullOrEmpty(d.ID))
                         .Select(d => d.ID)
                         .ToList();

            // 执行批量修改
            int updatedRows = bts.UpdateData(idList);
        }

        private static async Task<bool> PublishData(List<ZXJDataModel> data)
        {
            try
            {
                var payload = JsonConvert.SerializeObject(data);
                var message = new MqttApplicationMessageBuilder()
                    .WithTopic(MqttTopic)
                    .WithPayload(payload)
                    .WithQualityOfServiceLevel(MQTTnet.Protocol.MqttQualityOfServiceLevel.AtLeastOnce)
                    .Build();

                var result = await _mqttClient.PublishAsync(message);
                return result.ReasonCode == MQTTnet.Client.Publishing.MqttClientPublishReasonCode.Success;
            }
            catch
            {
                return false;
            }
        }
        /// <summary>
        /// 查看点检记录
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void buttonSearchDJ_Click(object sender, EventArgs e)
        {
            //// 创建并显示查询窗体
            //using (DJSearchForm searchForm = new DJSearchForm())
            //{
            //    searchForm.Size = new Size(1650, 750);
            //    searchForm.ShowDialog();
            //}
            // 创建查询条件对象
            SearchModel searchModel = new SearchModel
            {
                StartTime = dateTimePickerStart.Value,
                EndTime = dateTimePickerEnd.Value,
                CZRY = textBoxCZRY.Text.Trim()
            };

            // 使用查询条件刷新数据
            BindWorkOrdersToDataGridView(searchModel);
        }

       
        private void BindWorkOrdersToDataGridView(SearchModel searchCondition = null)
        {
            try
            {
                // 1. 从配置读取设备编码
                //string machineId = ConfigurationManager.AppSettings["DeviceCode"];
                dataGridView3.ColumnHeadersHeightSizeMode = DataGridViewColumnHeadersHeightSizeMode.EnableResizing;
                dataGridView3.ColumnHeadersHeight = 45;
                //if (string.IsNullOrEmpty(machineId))
                //{
                //    MessageBox.Show("设备编码未配置！");
                //    return;
                //}
                // 使用传入的查询条件（如果为空则创建默认条件）
                var condition = searchCondition ?? new SearchModel();
                // 2. 调用接口获取数据
                List<DJDayDataModelList> workOrders = bts.GetDayDJList(condition);
                
                // 3. 绑定到DataGridView
                if (workOrders != null && workOrders.Count > 0)
                {
                    // 绑定数据源
                    dataGridView3.DataSource = workOrders;
                    dataGridView3.RowTemplate.Height = 45;
                    // 配置列映射（字段名 -> 列名）
                    //dataGridView1.AutoGenerateColumns = false; // 禁止自动生成列
                    // 设置开始时间和结束时间列的格式
                    //if (dataGridView3.Columns.Contains("Column5"))
                    //{
                    //    dataGridView3.Columns["Column5"].DefaultCellStyle.Format = "yyyy-MM-dd HH:mm:ss";
                    //    dataGridView3.Columns["Column5"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                    //}
                    if (dataGridView3.Columns.Contains("Column3"))
                    {
                        dataGridView3.Columns["Column3"].DefaultCellStyle.Format = "yyyy-MM-dd";
                        dataGridView3.Columns["Column3"].DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter;
                        // 确保使用格式提供程序（关键）
                        //dataGridView3.Columns["Column3"].DefaultCellStyle.FormatProvider = CultureInfo.InvariantCulture;
                    }
                    // 强制刷新显示（可选）
                    //dataGridView3.Refresh();


                    //Message.Text = "";
                }
                else
                {
                    //MessageBox.Show("未查询到工单数据");
                    //Message.Text = "未查询到工单排程数据";
                    //Message.ForeColor = Color.Red;
                }
            }
            catch (Exception ex)
            {
                //MessageBox.Show($"加载数据失败: {ex.Message}");
                //Message.Text = $"加载数据失败: {ex.Message}";
                //Message.ForeColor = Color.Red;
            }
        }

        private void dataGridView3_CellContentClick(object sender, DataGridViewCellEventArgs e)
        {
            // 忽略标题行和无效点击
            if (e.RowIndex < 0 || e.ColumnIndex < 0) return;

            // 获取"时间"列的值（假设列名为"时间"）
            string timeValue = dataGridView3.Rows[e.RowIndex].Cells["Column4"].Value?.ToString();

            if (!string.IsNullOrEmpty(timeValue))
            {
                time = timeValue;  // 存储时间值
                OpenAddForm();          // 跳转到新窗体
                //DJSearchForm searchForm = new DJSearchForm();
                //searchForm.ShowDialog(this);
            }
            else
            {
                MessageBox.Show("时间数据为空，无法跳转");
            }
        }

        private void OpenAddForm()
        {
            // 1. 创建承载窗体
            //Form hostForm = new Form();
            //hostForm.Text = "工单详情";  // 设置窗体标题
            //hostForm.Size = new Size(1650, 650);
            //hostForm.StartPosition = FormStartPosition.CenterScreen;  // 关键居中设置

            // 2. 实例化用户控件
            DJSearchForm searchForm = new DJSearchForm();
            searchForm.Size = new Size(1650, 650);

            // 3. 传递工单号到用户控件（需在DJAddUserControl中添加接收方法）
            searchForm.SetMachineId(time);

            // 4. 设置用户控件填充窗体
            //dJAddUserControl.Dock = DockStyle.Fill;

            // 5. 将控件添加到窗体
            //hostForm.Controls.Add(dJAddUserControl);

            // 6. 显示窗体
            //hostForm.Show();
            searchForm.ShowDialog(this);
            //DJAddUserControl dJAddUserControl = new DJAddUserControl();
            //dJAddUserControl.Show();
        }

        // 添加Windows API导入
        [DllImport("user32.dll")]
        private static extern bool SetForegroundWindow(IntPtr hWnd);

        // 其他现有代码...

        // 添加显示屏幕键盘的方法
        private void ShowOnScreenKeyboard()
        {
            try
            {
                // 检查屏幕键盘是否已经在运行
                var oskProcess = Process.GetProcessesByName("osk").FirstOrDefault();

                if (oskProcess == null)
                {
                    // 启动屏幕键盘
                    Process.Start("osk.exe");
                }
                else
                {
                    // 如果已经在运行，将其带到前台
                    SetForegroundWindow(oskProcess.MainWindowHandle);
                }
            }
            catch (Exception ex)
            {
                // 如果无法启动屏幕键盘，可以尝试其他方法
                try
                {
                    // 尝试使用tabtip (Windows 10触摸键盘)
                    Process.Start("tabtip.exe");
                }
                catch
                {
                    MessageBox.Show("无法启动屏幕键盘: " + ex.Message);
                }
            }
        }

        // 添加Enter事件处理程序
        private void Control_Enter(object sender, EventArgs e)
        {
            ShowOnScreenKeyboard();
        }

    }
}
